<template>
  <div v-loading="loading" class="category-manage">
    <!-- tree start -->
    <!-- <div class="category-container">
      <div class="handle-box">
        <div class="filter-input">
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            size="small"
          />
        </div>
        <el-button
          type="text"
          round
          icon="el-icon-plus"
          class="add-btn"
          @click="add({isAddLevel1:true})"
        >新增根类目
        </el-button>
      </div>
      <div class="list-container">
        <el-tree
          ref="categoryTree"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :highlight-current="true"
          node-key="id"
          default-expand-all
          accordion
          @node-click="handleTree"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <el-button
              v-show="node.level<=2"
              type="text"
              class="add-btn"
              size="small"
              icon="el-icon-plus"
              @click.stop="add({node, data})"
            >
              子类目</el-button>
          </span>
        </el-tree>
      </div>
    </div> -->
    <!-- tree end -->

    <!-- form start -->
    <div class="form-container app-main-content-box">
      <div>
        <el-form
          ref="filterForm"
          :model="filterForm"
          inline
          label-width="100px"
          size="small"
        >
          <div>
            <el-form-item prop="title" label="分类名称：">
              <el-input
                v-model="filterForm.title"
                placeholder="请输入分类名称"
              />
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" round @click="search()"
                >搜 索</el-button
              >
              <el-button round @click="reset">重 置</el-button>
              <el-button
                type="primary"
                round
                @click="add()"
                v-if="mainShopStatus"
                >新增分类</el-button
              >
            </el-form-item>
          </div>
        </el-form>
      </div>
      <el-table
        :data="tabData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        default-expand-all
        border
      >
        <el-table-column prop="title" label="分类名称"></el-table-column>
        <el-table-column prop="count" label="菜品数量"></el-table-column>
        <el-table-column prop="ranking" label="序号">
          <template slot-scope="scope">
            <!-- {{scope.row.ranking}} -->
            <div>
              {{ scope.row.ranking }}
              <i
                v-if="mainShopStatus"
                class="el-icon-edit"
                @click="editRank(scope.$index, scope.row, 'edit')"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          fixed="right"
          v-if="mainShopStatus"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="del(scope.row)"
              >删除</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.level <= 2"
              size="small"
              @click="add(scope.row)"
              >新增</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div v-if="mode==='edit'&&activeTreeNode||mode==='add'&&(activeTreeNode||isAddLevel1)">
        <div>
          <AppMainTitle :title="mode === 'add' ? activeTreeNode?'新增子类目':'新增根类目' : '编辑类目'" />
        </div>
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="130px"
          size="small"
        >
          <el-form-item
            v-if="mode === 'edit' && activeTreeNode && activeTreeNode.level !== 1"
            label="上级类目："
          >{{ activeTreeNode.parent.data.title }}
          </el-form-item>
          <el-form-item
            v-if="mode === 'add' && activeTreeNode"
            label="上级类目："
          >{{ activeTreeNode.data.title }}
          </el-form-item>
          <el-form-item label="类别名称：" prop="title">
            <el-input
              v-model.trim="form.title"
              class="w-300-h-32"
              maxlength="10"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="类别编码：">
            <el-input
              v-model="form.categoryNo"
              class="w-300-h-32"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="类目商品属性：" prop="specList">
            <el-card
              v-for="(item, index) in form.specList"
              :key="'spec-' + index"
              class="spec-card"
            >
              <div slot="header" class="clearfix">
                <span>{{ item.title }}</span>
                <el-button
                  style="float: right"
                  type="text"
                  @click="delSpec(index)"
                >删除
                </el-button>
              </div>
              <el-form-item
                :prop="'specList.' + index + '.attrList'"
                :rules="rules.attrList"
              >
                <el-tag
                  v-for="(tagItem, tagIndex) in item.attrList"
                  :key="'attr-' + tagIndex"
                  :disable-transitions="false"
                  closable
                  @close="closeAttr(item.attrList, tagIndex)"
                >{{ tagItem.title }}
                </el-tag>
                <div>
                  <el-input
                    v-if="item.inputVisible"
                    ref="saveAttrInput"
                    v-model="item.inputValue"
                    class="w-450-h-32"
                    size="small"
                    placeholder="请输入属性选项"
                    maxlength="30"
                    show-word-limit
                    @keyup.enter.native="addAttr(item)"
                    @blur="addAttr(item)"
                  />
                  <el-button
                    v-else
                    size="small"
                    style="height: 32px"
                    @click="showAttrInput(item)"
                  >+ 增加类目属性选项
                  </el-button>
                </div>
              </el-form-item>
            </el-card>

            <el-input
              v-if="specInputVisible"
              ref="saveSpecInput"
              v-model.trim="form.specInputValue"
              class="w-300-h-32"
              size="small"
              placeholder="请输入属性名"
              maxlength="10"
              show-word-limit
              @keyup.enter.native="addSpec"
              @blur="addSpec"
            />

            <el-button
              v-else
              type="text"
              icon="el-icon-plus"
              style="height: 32px"
              @click="showSpecInput"
            >增加类目商品属性
            </el-button>
          </el-form-item>
          <el-form-item label="类目商品参数：">
            <el-card v-if="form.paramList.length > 0" class="spec-card">
              <el-tag
                v-for="(paramItem, paramIndex) in form.paramList"
                :key="'param-' + paramIndex"
                :disable-transitions="false"
                closable
                @close="closeParam(paramIndex)"
              >{{ paramItem }}
              </el-tag>
              <div>
                <el-input
                  v-if="paramInputVisible"
                  ref="saveParamInput"
                  v-model.trim="form.paramInputValue"
                  class="w-300-h-32"
                  size="small"
                  placeholder="请输入参数"
                  maxlength="10"
                  show-word-limit
                  @keyup.enter.native="addParams"
                  @blur="addParams"
                />
                <el-button
                  v-else
                  size="small"
                  style="height: 32px"
                  @click="showParamInput"
                >+ 增加类目商品参数
                </el-button>
              </div>
            </el-card>

            <div v-else>
              <el-input
                v-if="paramInputVisible"
                ref="saveParamInput"
                v-model.trim="form.paramInputValue"
                class="w-300-h-32"
                size="small"
                placeholder="请输入参数"
                maxlength="10"
                show-word-limit
                @keyup.enter.native="addParams"
                @blur="addParams"
              />
              <el-button
                v-else
                type="text"
                icon="el-icon-plus"
                style="height: 32px"
                @click="showParamInput"
              >增加类目商品参数
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" round @click="submit">保 存</el-button>
            <el-button
              v-show="mode === 'edit'"
              round
              @click="reset"
            >重 置
            </el-button>
            <el-button
              v-show="mode === 'edit'"
              round
              @click="del"
            >删 除
            </el-button>
          </el-form-item>
        </el-form>
      </div>
       <div v-else class="empty-form-tips">
        请选择类目
      </div> -->
    <!-- </div> -->
    <!-- form end -->
    <DialogEditClassify ref="DialogEditClassify" @upData="fetchData" />
  </div>
</template>

<script>
import {
  categoryDetail,
  categoryTree,
  addCategory,
  delCategory,
  updateCategory,
  getSpecId,
  getAttrId,
} from "@/views/wxaMallModule/api/category";
import { batchModifyStoreSkus } from "@/views/wxaMallModule/api/productPublic";
import {
  validateCustomTwoDecimal,
  validateCustomPositiveInt,
} from "@/utils/validate";
import DialogEditClassify from "./DialogEditClassify";
import { mapState } from "vuex";

export default {
  data() {
    return {
      // 校验规则相关
      rules: {
        title: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
        categoryNo: [
          { required: true, message: "请输入类别编码", trigger: "blur" },
        ],
        attrList: [
          {
            type: "array",
            required: true,
            message: "请至少设置一种属性选项",
            // trigger: "change",
          },
        ],
      },
      // 配置
      treeProps: {
        label: "title",
      },
      // 状态
      loading: false,
      paramInputVisible: false,
      specInputVisible: false,
      isAddLevel1: false,
      // 数据
      filterText: "",
      treeData: [],
      tabData: [],
      mode: "add",
      activeTreeNode: null,
      activeTreeData: null,
      form: {
        categoryNo: "",
        icon: "",
        parentId: 0,
        parentIds: "",
        ranking: "",
        paramList: [],
        specList: [],
        title: "",
        specInputValue: "",
        paramInputValue: "",
      },

      filterForm: {
        title: "",
      },
    };
  },
  components: {
    DialogEditClassify,
  },
  computed: {
    ...mapState({
      mainShopStatus: (state) => state.user.mainShopStatus,
    }),
  },
  watch: {
    filterText(val) {
      this.$refs.categoryTree.filter(val);
    },
  },
  created() {},
  mounted() {
    this.fetchData();
  },
  methods: {
    /**
     * 数据组
     */
    // 获取tree列表
    fetchData() {
      this.loading = true;
      categoryTree()
        .then((res) => {
          this.treeData = res.data;
          this.tabData = JSON.parse(JSON.stringify(this.treeData));
          // this.$nextTick(() => {
          //   if (this.activeTreeData) {
          //     this.$refs.categoryTree.setCurrentKey(this.activeTreeData.id);
          //   }
          // });
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },

    // 获取详情
    getDetail(id) {
      categoryDetail({ categoryId: id })
        .then((res) => {
          res.data.specList.map((v) => {
            v.inputVisible = false;
            v.inputValue = "";
          });
          this.form = res.data;
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          });
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },

    // 获取

    /**
     * 按钮组
     */
    // 新增类目
    // add({ node, data, isAddLevel1 = false }) {
    add(data) {
      if (data) {
        data.type = "add";
      }
      this.$refs.DialogEditClassify.openDialog(data);

      // console.log(node,data)
      // this.mode = "add";
      // if (!isAddLevel1) {
      //   this.isAddLevel1 = false;
      //   this.activeTreeNode = node;
      //   this.activeTreeData = data;
      //   this.defaultForm(false);
      //   this.form.parentId = data.id;
      //   this.$nextTick(() => {
      //     this.$refs.form.clearValidate();
      //   });
      // } else {
      //   this.isAddLevel1 = true;
      //   this.defaultForm(true);
      // }
    },

    // 点击tree
    // handleTree(data, node) {
    //   console.log("handleTree", data, node);
    //   if (data.id === this.form.id) {
    //     // this.$refs.categoryTree.setCurrentKey(null)
    //     // this.defaultForm(true)
    //     return;
    //   }
    //   this.loading = true;
    //   this.mode = "edit";
    //   this.activeTreeNode = node;
    //   this.activeTreeData = data;
    //   this.getDetail(data.id);
    // },

    // 显示specInput
    // showSpecInput() {
    //   this.specInputVisible = true;
    //   this.$nextTick(() => {
    //     this.$refs.saveSpecInput.$refs.input.focus();
    //   });
    // },

    // 删除spec
    // delSpec(index) {
    //   this.form.specList.splice(index, 1);
    // },

    // 新增spec
    // addSpec() {
    //   const inputValue = this.form.specInputValue;
    //   if (inputValue) {
    //     const flag = this.form.specList.some((v) => {
    //       if (inputValue === v.title) {
    //         return true;
    //       }
    //     });
    //     if (flag) {
    //       this.specInputVisible = false;
    //       this.form.specInputValue = "";
    //       return;
    //     }
    //     getSpecId({ title: inputValue })
    //       .then((res) => {
    //         this.form.specList.push({
    //           title: inputValue,
    //           id: res.data,
    //           attrList: [],
    //           inputVisible: false,
    //           inputValue: "",
    //         });
    //         this.specInputVisible = false;
    //         this.form.specInputValue = "";
    //       })
    //       .catch((err) => {})
    //       .finally(() => {});
    //   } else {
    //     this.specInputVisible = false;
    //     this.form.specInputValue = "";
    //   }
    // },

    // 显示attrInput
    // showAttrInput(item) {
    //   // 其它移除
    //   this.form.specList.forEach((v) => {
    //     if (v.id != item.id) {
    //       v.inputVisible = false;
    //     }
    //   });
    //   // 当前激活
    //   item.inputVisible = true;
    //   this.$nextTick(() => {
    //     this.$refs.saveAttrInput[0].$refs.input.focus();
    //   });
    // },

    // // 新增attr
    // addAttr(row) {
    //   const inputValue = row.inputValue;
    //   if (inputValue) {
    //     const flag = row.attrList.some((v) => {
    //       if (inputValue === v.title) {
    //         return true;
    //       }
    //     });
    //     if (flag) {
    //       row.inputVisible = false;
    //       row.inputValue = "";
    //       return;
    //     }
    //     getAttrId({ specId: row.id, title: inputValue })
    //       .then((res) => {
    //         row.attrList.push({
    //           title: inputValue,
    //           id: res.data,
    //         });
    //         // row.inputVisible = false;
    //         row.inputValue = "";
    //       })
    //       .catch((err) => {})
    //       .finally(() => {});
    //   } else {
    //     row.inputVisible = false;
    //     row.inputValue = "";
    //   }
    // },

    // 关闭attr
    // closeAttr(row, index) {
    //   row.splice(index, 1);
    // },

    // // 显示attrInput
    // showParamInput() {
    //   this.paramInputVisible = true;
    //   this.$nextTick(() => {
    //     this.$refs.saveParamInput.$refs.input.focus();
    //   });
    // },

    // // 新增商品参数
    // addParams() {
    //   const inputValue = this.form.paramInputValue;
    //   if (inputValue) {
    //     this.form.paramList.push(inputValue);
    //     this.form.paramList = [...new Set(this.form.paramList)];
    //     this.form.paramInputValue = "";
    //   } else {
    //     this.paramInputVisible = false;
    //     this.form.paramInputValue = "";
    //   }
    // },

    // // 关闭参数
    // closeParam(index) {
    //   this.form.paramList.splice(index, 1);
    // },

    // // 保存
    // submit() {
    //   this.$refs.form.validate((valid) => {
    //     if (valid) {
    //       this.loading = true;
    //       if (this.form.id) {
    //         updateCategory(this.form)
    //           .then((res) => {
    //             this.fetchData();
    //             this.$notify({
    //               title: "成功",
    //               message: "更新成功",
    //               type: "success",
    //               duration: 2000,
    //               offset: 40,
    //             });
    //           })
    //           .finally(() => {
    //             this.loading = false;
    //           });
    //       } else {
    //         addCategory(this.form)
    //           .then((res) => {
    //             this.fetchData();
    //             this.$notify({
    //               title: "成功",
    //               message: "新增成功",
    //               type: "success",
    //               duration: 2000,
    //               offset: 40,
    //             });
    //             // 清空数据
    //             this.form = {
    //               categoryNo: "",
    //               icon: "",
    //               parentId: this.form.parentId,
    //               parentIds: this.form.parentIds,
    //               ranking: "",
    //               paramList: [],
    //               specList: [],
    //               title: "",
    //               specInputValue: "",
    //               paramInputValue: "",
    //             };
    //           })
    //           .finally(() => {
    //             this.loading = false;
    //           });
    //       }
    //     }
    //   });
    // },

    // // 删除
    del(row) {
      this.$confirm(`您确定要删除类目：${row.title}，是否继续?`, "温馨提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        roundButton: true,
      }).then(() => {
        this.loading = true;
        delCategory({ categoryId: row.id })
          .then((res) => {
            // this.$refs.categoryTree.remove(this.activeTreeData);
            // this.defaultForm();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
              offset: 40,
            });
            this.fetchData();
          })
          .catch((err) => {})
          .finally(() => {
            this.loading = false;
          });
      });
    },
    search() {
      let { title } = this.filterForm;
      if (!title) {
        this.tabData = JSON.parse(JSON.stringify(this.treeData));
        return;
      }
      this.tabData = [];
      this.treeData.forEach((e) => {
        if (e.title.toLowerCase().indexOf(title.toLowerCase()) != -1) {
          this.tabData.push(e);
        } else if (e.children.length > 0) {
          let child = e.children;
          child.forEach((k) => {
            if (k.title.toLowerCase().indexOf(title.toLowerCase()) != -1) {
              this.tabData.push(e);
            } else if (k.children.length > 0) {
              let childScoend = k.children;
              childScoend.forEach((f) => {
                if (f.title.toLowerCase().indexOf(title.toLowerCase()) != -1) {
                  this.tabData.push(e);
                }
              });
            }
          });
        }
      });
    },

    // 重置
    reset() {
      this.filterForm.title = "";
      this.tabData = JSON.parse(JSON.stringify(this.treeData));
    },
    /**
     * 状态组
     */
    /**
     * 方法组
     */
    // 筛选tree
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.title.indexOf(value) !== -1;
    // },

    // // 默认数据
    // defaultForm(clearActive = true) {
    //   if (clearActive) {
    //     this.activeTreeNode = null;
    //     this.activeTreeData = null;
    //   }
    //   this.mode = "add";
    //   this.specInputVisible = "";
    //   this.paramInputVisible = "";
    //   this.form = {
    //     categoryNo: "",
    //     icon: "",
    //     parentId: 0,
    //     parentIds: "",
    //     ranking: "",
    //     paramList: [],
    //     specList: [],
    //     title: "",
    //     specInputValue: "",
    //     paramInputValue: "",
    //   };
    // },
    edit(data) {
      data.type = "edit";
      this.$refs.DialogEditClassify.openDialog(data);
    },
    editRank(index, row, type) {
      const _this = this;
      this.$prompt(`请输入序号`, {
        confirmButtonText: "保存",
        cancelButtonText: "取消",
        inputValidator: this.validateStock,
      })
        .then(({ value }) => {
          let { id } = row;
          row.ranking = value;
          updateCategory(row).then((res) => {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000,
              offset: 40,
            });
            this.fetchData();
          });
        })
        .catch(() => {});
    },
    validateStock(val) {
      if (!val) {
        return "请输入序号";
      } else if (val == 0) {
        return;
      } else if (!validateCustomPositiveInt(val, 6)) {
        return "请输入正整数（最大值999999）";
      }
    },
    //
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/*容器*/
.category-manage {
  display: flex;

  .category-container {
    margin-right: 10px;
  }

  .form-container {
    flex: 1;
  }
}

/* 类目 */
.category-container {
  background-color: #fff;
  padding: 24px 0 10px;
  border-radius: 5px;

  .handle-box {
    padding: 0 10px;
  }

  .list-container {
    overflow: auto;
    height: calc(100vh - 184px);
    padding: 0 10px;
    font-size: 14px;
  }
  .custom-tree-node {
    width: 100%;
    .add-btn {
      margin-left: 2px;
      visibility: hidden;
      height: 32px;
    }
    &:hover {
      .add-btn {
        visibility: visible;
      }
    }
  }
}

/* 表单 */
.form-container {
  .w-300-h-32 {
    width: 300px;
    height: 32px;
  }

  .w-450-h-32 {
    width: 450px;
    height: 32px;
  }

  .spec-card {
    width: 600px;
    margin-bottom: 10px;

    ::v-deep .el-card__header {
      padding: 5px 20px;
    }

    .el-tag {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}

//空标签
.empty-form-tips {
  margin: 100px 0;
  text-align: center;
  font-size: 14px;
  color: #606266;
}
</style>
